import { getConfig } from "@/config";
import { type menuType, routerArrays } from "@/layout/types";
import { useMultiTagsStoreHook } from "@/store/modules/multiTags";
import { usePermissionStoreHook } from "@/store/modules/permission";
import { type DataInfo, userKey } from "@/utils/auth";
import { buildHierarchyTree } from "@/utils/tree";
import {
  cloneDeep,
  intersection,
  isAllEmpty,
  isIncludeAllChildren,
  isString,
  storageLocal
} from "@pureadmin/utils";
import { useTimeoutFn } from "@vueuse/core";
import { isProxy, toRaw } from "vue";
import {
  type RouteComponent,
  type RouteRecordRaw,
  type RouterHistory,
  createWebHashHistory,
  createWebHistory
} from "vue-router";
import { router } from "./index";
const IFrame = () => import("@/layout/frame.vue");
// https://cn.vitejs.dev/guide/features.html#glob-import
const modulesRoutes = import.meta.glob("/src/views/**/*.{vue,tsx}");

// 动态路由
// import { getAsyncRoutes } from "@/api/routes";
import { getLoginInfo } from "@/api/user";
// 导入动态路由定义库
import asyncRouteDefinitions from "./modules/async";

function handRank(routeInfo: any) {
  const { name, path, parentId, meta } = routeInfo;
  return isAllEmpty(parentId)
    ? isAllEmpty(meta?.rank) ||
      (meta?.rank === 0 && name !== "Home" && path !== "/")
      ? true
      : false
    : false;
}

/** 按照路由中meta下的rank等级升序来排序路由 */
function ascending(arr: any[]) {
  arr.forEach((v, index) => {
    // 当rank不存在时，根据顺序自动创建，首页路由永远在第一位
    if (handRank(v)) v.meta.rank = index + 2;
  });
  return arr.sort(
    (a: { meta: { rank: number } }, b: { meta: { rank: number } }) => {
      return a?.meta?.rank - b?.meta?.rank;
    }
  );
}

/** 过滤meta中showLink为false的菜单 */
function filterTree(data: RouteComponent[]) {
  const newTree = cloneDeep(data).filter(
    (v: { meta: { showLink: boolean } }) => v.meta?.showLink !== false
  );
  newTree.forEach(
    (v: { children }) => v.children && (v.children = filterTree(v.children))
  );
  return newTree;
}

/** 过滤children长度为0的的目录，当目录下没有菜单时，会过滤此目录，目录没有赋予roles权限，当目录下只要有一个菜单有显示权限，那么此目录就会显示 */
function filterChildrenTree(data: RouteComponent[]) {
  const newTree = cloneDeep(data).filter((v: any) => v?.children?.length !== 0);
  newTree.forEach(
    (v: { children }) => v.children && (v.children = filterTree(v.children))
  );
  return newTree;
}

/** 判断两个数组彼此是否存在相同值 - 已注释权限检查 */
function isOneOfArray(a: Array<string>, b: Array<string>) {
  // 注释权限检查逻辑，直接返回true允许所有访问
  // return Array.isArray(a) && Array.isArray(b)
  //   ? intersection(a, b).length > 0
  //     ? true
  //     : false
  //   : true;

  // 跳过权限检查，允许所有菜单显示
  return true;
}

/** 从localStorage里取出当前登录用户的角色roles，过滤无权限的菜单 - 已注释权限检查 */
function filterNoPermissionTree(data: RouteComponent[]) {
  // 注释权限过滤逻辑，直接返回所有数据
  // const currentRoles =
  //   storageLocal().getItem<DataInfo<number>>(userKey)?.roles ?? [];
  // const newTree = cloneDeep(data).filter((v: any) =>
  //   isOneOfArray(v.meta?.roles, currentRoles)
  // );
  // newTree.forEach(
  //   (v: any) => v.children && (v.children = filterNoPermissionTree(v.children))
  // );
  // return filterChildrenTree(newTree);

  // 跳过权限检查，只过滤空子菜单
  // return filterChildrenTree(data);
  return data;
}

/** 通过指定 `key` 获取父级路径集合，默认 `key` 为 `path` */
function getParentPaths(value: string, routes: RouteRecordRaw[], key = "path") {
  // 深度遍历查找
  function dfs(routes: RouteRecordRaw[], value: string, parents: string[]) {
    for (let i = 0; i < routes.length; i++) {
      const item = routes[i];
      // 返回父级path
      if (item[key] === value) return parents;
      // children不存在或为空则不递归
      if (!item.children || !item.children.length) continue;
      // 往下查找时将当前path入栈
      parents.push(item.path);

      if (dfs(item.children, value, parents).length) return parents;
      // 深度遍历查找未找到时当前path 出栈
      parents.pop();
    }
    // 未找到时返回空数组
    return [];
  }

  return dfs(routes, value, []);
}

/** 查找对应 `path` 的路由信息 */
function findRouteByPath(path: string, routes: RouteRecordRaw[]) {
  let res = routes.find((item: { path: string }) => item.path == path);
  if (res) {
    return isProxy(res) ? toRaw(res) : res;
  } else {
    for (let i = 0; i < routes.length; i++) {
      if (
        routes[i].children instanceof Array &&
        routes[i].children.length > 0
      ) {
        res = findRouteByPath(path, routes[i].children);
        if (res) {
          return isProxy(res) ? toRaw(res) : res;
        }
      }
    }
    return null;
  }
}

function addPathMatch() {
  if (!router.hasRoute("pathMatch")) {
    router.addRoute({
      path: "/:pathMatch(.*)",
      name: "pathMatch",
      redirect: "/error/404"
    });
  }
}

/** 处理动态路由（后端返回的路由） - 简化版本 */
function handleAsyncRoutes(routeList) {
  console.log("🚀 开始处理动态路由");

  if (!routeList || routeList.length === 0) {
    usePermissionStoreHook().handleWholeMenus([]);
    addPathMatch();
    return;
  }

  // 过滤页面类型路由
  const pageRoutes = routeList.filter(v => v.menuType === 2);
  console.log(`找到 ${pageRoutes.length} 个页面路由`);

  const matchedRoutes = [];

  // 简单匹配：直接在 asyncRouteDefinitions 中查找
  for (const backendRoute of pageRoutes) {
    const routePath = backendRoute.component;
    console.log(`匹配路由: ${routePath}`);

    // 直接在路由定义中查找匹配的路由
    const matchedRoute = asyncRouteDefinitions.find(
      route => route.path === routePath
    );

    if (matchedRoute) {
      // 简单克隆并更新标题和图标
      const finalRoute = {
        ...matchedRoute,
        meta: {
          ...matchedRoute.meta,
          title: matchedRoute.meta.title,
          icon: backendRoute.icon,
          showLink: true,
          backstage: true
        }
      };
      matchedRoutes.push(finalRoute);
      console.log(`✅ 匹配成功: ${routePath}`);
    } else {
      console.warn(`❌ 未找到路由: ${routePath}`);
    }
  }

  // 添加路由到系统
  if (matchedRoutes.length > 0) {
    matchedRoutes.forEach(route => {
      try {
        console.log("📦 原始路由信息：", {
          path: route.path,
          name: route.name,
          component: route.component ? "已设置" : "未设置",
          children: route.children?.length || 0
        });

        // 处理路由组件
        const processedRoute = addAsyncRoutes([route])[0];

        console.log("🔧 处理后路由信息：", {
          path: processedRoute.path,
          name: processedRoute.name,
          component: processedRoute.component ? "已设置" : "未设置",
          children: processedRoute.children?.length || 0
        });

        // 添加到Vue Router
        if (!router.hasRoute(processedRoute.name)) {
          router.addRoute("Home", processedRoute);
          console.log(
            `✅ 已添加路由: ${String(processedRoute.name)} (${processedRoute.path})`
          );
        } else {
          console.warn(`⚠️ 路由名称已存在: ${String(processedRoute.name)}`);
        }
      } catch (error) {
        console.error(`❌ 添加路由失败: ${route.path}`, error);
      }
    });

    // 设置菜单数据
    const menus = matchedRoutes.map(route => ({
      path: route.path,
      name: route.name,
      value: route.name || route.path,
      meta: {
        ...route.meta,
        showLink: true, // 确保菜单显示
        title: route.meta?.title || route.name
      },
      children: route.children || []
    }));

    console.log("🔧 设置菜单数据：", menus);
    usePermissionStoreHook().handleWholeMenus(menus);
  } else {
    usePermissionStoreHook().handleWholeMenus([]);
  }

  // 处理多标签页缓存
  if (!useMultiTagsStoreHook().getMultiTagsCache) {
    useMultiTagsStoreHook().handleTags("equal", [
      ...routerArrays,
      ...usePermissionStoreHook().flatteningRoutes.filter(
        v => v?.meta?.fixedTag
      )
    ]);
  }

  addPathMatch();

  // 调试：输出所有注册的路由
  const allRoutes = router.getRoutes();
  console.log("🎉 动态路由处理完成！");
  console.log(
    "📋 当前所有注册的路由：",
    allRoutes.map(r => ({
      name: r.name,
      path: r.path,
      components: r.components ? "已设置" : "未设置"
    }))
  );

  // 调试：输出菜单数据
  const currentMenus = usePermissionStoreHook().wholeMenus;
  console.log("🍔 当前菜单数据：", currentMenus);
}

/** 初始化路由（`new Promise` 写法防止在异步请求中造成无限循环）*/
function initRouter(): Promise<any> {
  if (getConfig()?.CachingAsyncRoutes) {
    // 开启动态路由缓存本地localStorage
    const key = "async-routes";
    const asyncRouteList = storageLocal().getItem(key) as any;
    if (asyncRouteList && asyncRouteList?.length > 0) {
      return new Promise(resolve => {
        handleAsyncRoutes(asyncRouteList);
        resolve(router);
      });
    } else {
      return new Promise(resolve => {
        getLoginInfo().then(({ data }) => {
          console.log("mujin data :>> ", data);
          handleAsyncRoutes(cloneDeep(data));
          storageLocal().setItem(key, data);
          resolve(router);
        });
      });
    }
  } else {
    return new Promise(resolve => {
      fetchLoginInfo(() => {
        resolve(router);
      });
    });
  }
}

export function fetchLoginInfo(cb?: any) {
  const key = "user-info";
  getLoginInfo().then(({ data }) => {
    const { menuList, ...rest } = data;
    storageLocal().setItem(key, rest);
    if (cb) {
      handleAsyncRoutes(cloneDeep(menuList));
      cb?.(router);
    }
  });
}

/**
 * 将多级嵌套路由处理成一维数组
 * @param routesList 传入路由
 * @returns 返回处理后的一维路由
 */
function formatFlatteningRoutes(routesList: RouteRecordRaw[]) {
  if (routesList.length === 0) return routesList;
  let hierarchyList = buildHierarchyTree(routesList);
  for (let i = 0; i < hierarchyList.length; i++) {
    if (hierarchyList[i].children) {
      hierarchyList = hierarchyList
        .slice(0, i + 1)
        .concat(hierarchyList[i].children, hierarchyList.slice(i + 1));
    }
  }
  return hierarchyList;
}

/**
 * 一维数组处理成多级嵌套数组（三级及以上的路由全部拍成二级，keep-alive 只支持到二级缓存）
 * https://github.com/pure-admin/vue-pure-admin/issues/67
 * @param routesList 处理后的一维路由菜单数组
 * @returns 返回将一维数组重新处理成规定路由的格式
 */
function formatTwoStageRoutes(routesList: RouteRecordRaw[]) {
  if (routesList.length === 0) return routesList;
  const newRoutesList: RouteRecordRaw[] = [];
  routesList.forEach((v: RouteRecordRaw) => {
    if (v.path === "/") {
      newRoutesList.push({
        component: v.component,
        name: v.name,
        path: v.path,
        redirect: v.redirect,
        meta: v.meta,
        children: []
      });
    } else {
      newRoutesList[0]?.children.push({ ...v });
    }
  });
  return newRoutesList;
}

/** 处理缓存路由（添加、删除、刷新） */
function handleAliveRoute({ name }: ToRouteType, mode?: string) {
  switch (mode) {
    case "add":
      usePermissionStoreHook().cacheOperate({
        mode: "add",
        name
      });
      break;
    case "delete":
      usePermissionStoreHook().cacheOperate({
        mode: "delete",
        name
      });
      break;
    case "refresh":
      usePermissionStoreHook().cacheOperate({
        mode: "refresh",
        name
      });
      break;
    default:
      usePermissionStoreHook().cacheOperate({
        mode: "delete",
        name
      });
      useTimeoutFn(() => {
        usePermissionStoreHook().cacheOperate({
          mode: "add",
          name
        });
      }, 100);
  }
}

/** 过滤后端传来的动态路由 重新生成规范路由 */
/** 处理动态路由组件 - 简化版本，保持原有组件定义 */
function addAsyncRoutes(arrRoutes: Array<RouteRecordRaw>) {
  if (!arrRoutes || !arrRoutes.length) return [];

  arrRoutes.forEach((v: RouteRecordRaw) => {
    // 标识为后端动态路由
    if (v.meta) {
      v.meta.backstage = true;
    }

    // 设置父级name（如果没有的话）
    if (v?.children && v.children.length && !v.name) {
      v.name = (v.children[0].name as string) + "Parent";
    }

    // 递归处理子路由
    if (v?.children && v.children.length) {
      addAsyncRoutes(v.children);
    }
  });

  return arrRoutes;
}

/** 获取路由历史模式 https://next.router.vuejs.org/zh/guide/essentials/history-mode.html */
function getHistoryMode(routerHistory): RouterHistory {
  // len为1 代表只有历史模式 为2 代表历史模式中存在base参数 https://next.router.vuejs.org/zh/api/#%E5%8F%82%E6%95%B0-1
  const historyMode = routerHistory.split(",");
  const leftMode = historyMode[0];
  const rightMode = historyMode[1];
  // no param
  if (historyMode.length === 1) {
    if (leftMode === "hash") {
      return createWebHashHistory("");
    } else if (leftMode === "h5") {
      return createWebHistory("");
    }
  } //has param
  else if (historyMode.length === 2) {
    if (leftMode === "hash") {
      return createWebHashHistory(rightMode);
    } else if (leftMode === "h5") {
      return createWebHistory(rightMode);
    }
  }
}

/** 获取当前页面按钮级别的权限 */
function getAuths(): Array<string> {
  return router.currentRoute.value.meta.auths as Array<string>;
}

/** 是否有按钮级别的权限（根据路由`meta`中的`auths`字段进行判断）- 已注释权限检查 */
function hasAuth(value: string | Array<string>): boolean {
  // 注释权限检查逻辑，直接返回true允许所有访问
  // if (!value) return false;
  // /** 从当前路由的`meta`字段里获取按钮级别的所有自定义`code`值 */
  // const metaAuths = getAuths();
  // if (!metaAuths) return false;
  // const isAuths = isString(value)
  //   ? metaAuths.includes(value)
  //   : isIncludeAllChildren(value, metaAuths);
  // return isAuths ? true : false;

  // 跳过权限检查，允许所有按钮访问
  return true;
}

function handleTopMenu(route) {
  if (!route) return null;

  if (route.children && route.children.length > 0) {
    return route.redirect
      ? route.children.find(child => child.path === route.redirect) ||
          route.children[0]
      : route.children[0];
  }

  return route;
}

/** 获取所有菜单中的第一个菜单（顶级菜单）- 简化版本 */
function getTopMenu(tag = false): menuType {
  const wholeMenus = usePermissionStoreHook().wholeMenus;

  // 默认菜单
  const defaultMenu = {
    path: "/welcome",
    name: "Welcome",
    value: "welcome",
    meta: { title: "欢迎页", showLink: true, rank: 0 }
  };

  if (!wholeMenus || wholeMenus.length === 0) {
    tag && useMultiTagsStoreHook().handleTags("push", defaultMenu);
    return defaultMenu;
  }

  const firstMenu = wholeMenus[0];
  const topMenu = handleTopMenu(firstMenu) || defaultMenu;

  tag && useMultiTagsStoreHook().handleTags("push", topMenu);
  return topMenu;
}

export {
  addAsyncRoutes,
  addPathMatch,
  ascending,
  filterNoPermissionTree,
  filterTree,
  findRouteByPath,
  formatFlatteningRoutes,
  formatTwoStageRoutes,
  getAuths,
  getHistoryMode,
  getParentPaths,
  getTopMenu,
  handleAliveRoute,
  hasAuth,
  initRouter,
  isOneOfArray
};
